﻿#include "ThreeChess.h"

static void InitBoard(char board[][COL]) //初始化棋盘
{
	for (int i = 0; i < ROW; i++)
	{
		for (int j = 0; j < COL; j++)
		{
			board[i][j] = INIT;
		}
	}
}

static void ShowBoard(char board[][COL])  //显示棋盘
{
	system("cls");  //刷新界面
	printf("  ");
	for (int i = 0; i < COL; i++)
	{
		printf(" %2d ", i+1);
	}
	printf("\n  +-----------+\n");
	for (int i = 0; i < ROW; i++)
	{
		printf("%2d", i+1);
		for (int j = 0; j < COL; j++)
		{
			printf("| %c ", board[i][j]);
		}
		printf("|");
		printf("\n  +-----------+\n");
	}
}

static void UserMove(char board[][COL])  //用户操作
{
	int x = 0,y = 0;
	while (1)
	{
		printf("请输入你的落子坐标<x,y>:");
		scanf("%d %d", &x, &y);
		if (x<1 || y<1 || x>COL || y>ROW)
		{
			printf("输入坐标超出范围！请重新输入");
			continue;
		}
		if (board[x-1][y-1] == INIT)
		{
			board[x-1][y-1] = BLACK;
			break;
		}
		else
		{
			printf("输入的坐标已有落子！请重新输入");
		}
	}
}

static void PCMove(char board[][COL])  //电脑操作
{
	while (1)
	{
		int x = rand() % ROW;  //电脑的输入坐标是通过随机函数生成
		int y = rand() % COL;

        if (board[x][y] == INIT)
		{
			board[x][y] = WHITE;
			break;
		}
	}
}

static char Judge(char board[][COL])
{
	for (int i = 0; i < ROW; i++)  //判断三行是否有满足三子成线
	{
		if (board[i][0] == board[i][1] && \
			board[i][1] == board[i][2] && \
			board[i][0] != INIT)
		{
			return board[i][0];
		}
	}
	for (int j = 0; j < COL; j++)  //判断三列是否有满足三子成线
	{
		if (board[0][j] == board[1][j] && \
			board[1][j] == board[2][j] && \
			board[0][j] != INIT)
		{
			return board[0][j];
		}
	}
	//判断右斜方向
	if (board[0][0] == board[1][1] && \
		board[1][1] == board[2][2] && \
		board[1][1] != INIT)
	{
		return board[1][1];
	}
	//判断左斜方向
	if (board[0][2] == board[1][1] && \
		board[1][1] == board[2][0] && \
		board[1][1] != INIT)
		{
			return board[1][1];
		}
	for (int i = 0; i < ROW; i++)  //若棋盘未下满继续
	{
		for (int j = 0; j < COL; j++)
		{
			if (board[i][j] == INIT)
			{
				return NEXT;
			}
		}
	}
	return DRAW;  //棋盘已满但未有输赢结果
}

void ThreeChess() //人机对战 用户先走
{
	srand((unsigned long)time(NULL)); //生成随机数种子，为电脑操作函数做准备

	char board_1[ROW][COL];
	InitBoard(board_1);
	char result = 0;
	while (1)
	{
		ShowBoard(board_1);
		UserMove(board_1);
		result = Judge(board_1);
		if (result != NEXT)
		{
			break;
		}
		ShowBoard(board_1);
		PCMove(board_1);
		result = Judge(board_1);
		if (result != NEXT)
		{
			break;
		}
	}
	ShowBoard(board_1);
	switch (result)
	{
	case BLACK:
		printf("你赢了！\n");
		break;
	case WHITE:
		printf("你输了！\n");
		break;
	case DRAW:
		printf("平局！\n");
		break;
	default:
		printf("bug！\n");
		break;
	}
}